{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# numpy教程"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&ensp;&ensp;NumPy（Numerical Python的简称）是Python科学计算的基础包。它提供以下功能：  \n",
    "1.快速高效的多维数组对象ndarray。  \n",
    "2.用于对数组执行元素级计算以及直接对数组执行数学运算的函数。  \n",
    "3.用于读写硬盘上基于数组的数据集的工具。  \n",
    "4.线性代数运算、傅里叶变换以及随机数生成。  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## numpy矩阵和数组的区别"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "NumPy函数库中存在两种不同的数据类型（矩阵matrix和数组array），虽然它们很相似，但是执行相同的数学运算可能得到不同的结果。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0.00687137, 0.70330468, 0.20813727, 0.58129288],\n",
       "       [0.64796542, 0.85035907, 0.28790362, 0.13788007],\n",
       "       [0.09214624, 0.5744963 , 0.50535701, 0.89935095],\n",
       "       [0.66125405, 0.850663  , 0.25309954, 0.7324152 ]])"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#数组\n",
    "import numpy as np\n",
    "np.random.rand(4,4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "matrix([[ 83.93984274, -43.3654061 , -23.43214965,  -8.69993158],\n",
       "        [-23.73101426,  12.1595981 ,   5.27362283,   6.74862705],\n",
       "        [-52.19484808,  28.49460248,  14.67115409,   3.41597509],\n",
       "        [ 17.76753726, -10.04695963,  -2.74070474,  -4.35284874]])"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#矩阵\n",
    "randMat=np.mat(np.random.rand(4,4))  #调用mat()函数可以将数组转化为矩阵\n",
    "#.I操作符实现了矩阵求逆的运算\n",
    "randMat.I"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "matrix([[ 1.00000000e+00,  8.88178420e-16,  4.44089210e-16,\n",
       "          0.00000000e+00],\n",
       "        [ 1.77635684e-15,  1.00000000e+00,  1.77635684e-15,\n",
       "          0.00000000e+00],\n",
       "        [ 2.22044605e-15,  2.88657986e-15,  1.00000000e+00,\n",
       "          4.44089210e-16],\n",
       "        [ 8.88178420e-16, -4.44089210e-16,  6.66133815e-16,\n",
       "          1.00000000e+00]])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#矩阵的乘法\n",
    "invRandMat=randMat.I\n",
    "randMat*invRandMat\n",
    "#结果应该是单位矩阵，除了对角线是1，其余元素都是0，实际结果略有不同，留下了许多非常小的元素，这是计算机处理的误差结果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1., 0., 0., 0.],\n",
       "       [0., 1., 0., 0.],\n",
       "       [0., 0., 1., 0.],\n",
       "       [0., 0., 0., 1.]])"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#单位矩阵\n",
    "np.eye(4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1.创建数组"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "NumPy最重要的一个特点就是其N维数组对象（即ndarray），该对象是一个快速而灵活的大数据集容器。  \n",
    "ndarray是一个通用的同构数据多维容器，也就是说，其中的所有元素必须是相同类型的。  \n",
    "常用函数:  \n",
    "(1)shape（一个表示各维度大小的元组,如果是2维的话，shape[0]表示行，shape[1]表示列）==>(1,2)表示1行2列;  \n",
    "(2)dtype（一个用于说明数组数据类型的对象）;  \n",
    "(3)size(展示的是数组a的规模，就是a的元素个数为多少);  \n",
    "(4)ndim(就是数组a有几个维度，比如3就代表数组a有三个维度);  \n",
    "(5)arange(是Python内置函数range的数组版,类似内置的range，但返回的是一个ndarray而不是列表);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  1.1 使用np.array()直接创建"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([1, 2, 3])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.array([1,2,3])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.2 使用 np.ones()、np.zeros() 等方法 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([1., 1., 1.])"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.ones(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0., 0., 0.])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.zeros(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-1.60898476,  0.33710152,  1.0617532 ],\n",
       "       [-1.16154912, -0.41046716, -1.47526273]])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.random.randn(2,3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.数组运算"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.1 加减运算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2. 3.]\n",
      "[0. 1.]\n"
     ]
    }
   ],
   "source": [
    "data=np.array([1,2])\n",
    "ones=np.ones(2)\n",
    "print(data+ones)\n",
    "print(data-ones)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.2 数组乘以数值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([2, 4])"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data*2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.3 数组索引"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#只取一个\n",
    "data[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([1, 2])"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#取子串\n",
    "data[0:2]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.4 数组聚合"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "1\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "print(data.max())\n",
    "print(data.min())\n",
    "print(data.sum())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3.矩阵"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.1 创建矩阵"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 2]\n",
      " [3 4]]\n",
      "[[1. 1.]\n",
      " [1. 1.]\n",
      " [1. 1.]]\n",
      "[[0. 0.]\n",
      " [0. 0.]\n",
      " [0. 0.]]\n",
      "[[0.98627283 0.17182198]\n",
      " [0.46271515 0.82566967]\n",
      " [0.68514157 0.5003767 ]]\n"
     ]
    }
   ],
   "source": [
    "#直接创建\n",
    "print(np.array([[1,2],[3,4]]))\n",
    "#使用 np.ones()、np.zeros() 等方法\n",
    "print(np.ones((3,2)))\n",
    "print(np.zeros((3,2)))\n",
    "print(np.random.random((3,2)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.2 矩阵运算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[2. 3.]\n",
      " [4. 5.]]\n",
      "[[2. 3.]\n",
      " [4. 5.]]\n"
     ]
    }
   ],
   "source": [
    "data=np.array([[1,2],[3,4]])\n",
    "ones=np.ones((2,2))\n",
    "print(data+ones)\n",
    "\n",
    "ones_row=np.ones(2)\n",
    "print(data+ones_row)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.3 矩阵点积 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[3., 3.],\n",
       "       [7., 7.]])"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data.dot(ones)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[3., 3.],\n",
       "       [7., 7.]])"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.dot(data,ones)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.4 矩阵索引 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1, 2],\n",
       "       [3, 4]])"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "[1 2]\n"
     ]
    }
   ],
   "source": [
    "print(data[0,1])\n",
    "#取行\n",
    "print(data[0,0:])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([1, 3])"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#取列\n",
    "data[0:,0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.5 矩阵聚合"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4\n",
      "1\n",
      "10\n"
     ]
    }
   ],
   "source": [
    "#求最值\n",
    "print(data.max())\n",
    "print(data.min())\n",
    "print(data.sum())\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([3, 4])"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#按行聚合\n",
    "data.max(axis=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([2, 4])"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#按列聚合\n",
    "data.max(axis=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.6 矩阵转置"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1, 3],\n",
       "       [2, 4]])"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data.T"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.7 矩阵重塑"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1, 2, 3],\n",
       "       [4, 5, 6]])"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data=np.array([1,2,3,4,5,6])\n",
    "data.reshape(2,3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4.通用函数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "通用函数（即ufunc）是一种对ndarray中的数据执行元素级运算的函数。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.1 一元ufunc函数说明  \n",
    "    abs、fabs：计算整数、浮点数或复数的绝对值。对于非复数值，可以使用更快的fabs；  \n",
    "    sqrt：计算各元素的平方根。相当于arr** 0.5；  \n",
    "    square：计算各元素的平方。相当于arr** 2；  \n",
    "    exp：计算各元素的指数ex；  \n",
    "    log、log10、 log2、 log1p：分别为自然对数(底数为e)、底数为10的log、底数为2的log、log(1 + x)；  \n",
    "    sign：计算各元素的正负号: 1 (正数)、0 (零)、-1 (负数)；  \n",
    "    ceil：计算各元素的ceiling值，即大于等于该值的最小整数；  \n",
    "    floor：计算各元素的floor值，即小于等于该值的最大整数；  \n",
    "    rint：将各元素值四舍五入到最接近的整数，保留dtype；  \n",
    "    modf：将数组的小数和整数部分以两个独立数组的形式返回；  \n",
    "    isnan：返回一个表示“哪些值是NaN (这不是一个数字)”的布尔型数组；  \n",
    "    isfinite、isinf：分别返回一个表示“哪些元素是有穷的(非inf，非NaN)”或“哪些元素是无穷的”的布尔型数组；  \n",
    "    cos、cosh、 sin、 sinh、tan、tanh：普通型和双曲型三角函数；  \n",
    "    arccos、arccosh、 arcsin、arcsinh、arctan、 arctanh：反三角函数；  \n",
    "    logical_ not：计算各元素notx的真值。相当于-arr；\n",
    "   "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.2 二 元ufunc函数说明\n",
    "    add：将数组中对应的元素相加；   \n",
    "    subtract：从第一个数组中减去第二个数组中的元素；    \n",
    "    multiply：数组元素相乘；  \n",
    "    divide. floor_ _divide：除法或向下圆整除法(丢弃余数)；  \n",
    "    power：对第一个数组中的元素A，根据第二个数组中的相应元素B，计算A；  \n",
    "    maximum、fmax：元素级的最大值计算。fmax 将忽略NaN；  \n",
    "    minimum、fmin：元素级的最小值计算。fmin将忽略NaN；  \n",
    "    mod：元素级的求模计算(除法的余数)；  \n",
    "    copysign：将第二个数组中的值的符号复制给第一个数组中的值；  \n",
    "    greater、greater_ equal、less、less_ equal、equal、not_ equal：执行元素级的比较运算，最终产生布尔型数组。相当于中缀运算符>、>=、<. <=. ==、!=  \n",
    "    logical_ and、 logical _or、logical xor：执行元素级的真值逻辑运算。相当于中缀运算符&、| ^  \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5.线性代数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "常用函数： \n",
    "\n",
    "    (1)diag:以一维数组的形式返回方阵的对角线(或非对角线)元素，或将一维数组转换为方阵(非对角线元素为0)；  \n",
    "    (2)dot:矩阵点乘；  \n",
    "    (3)trace：计算对角线元素的和；  \n",
    "    (4)det：计算矩阵行列式；  \n",
    "    (5)eig:计算方阵的特征值和特征向量；  \n",
    "    (6)inv:计算方阵的逆；  \n",
    "    (7)pinv:计算矩阵的Moore-Penrose伪逆；  \n",
    "    (8)qr:计算QR分解；  \n",
    "    (9)svd:计算奇异值分解(SVD)；  \n",
    "    (10)solve:解线性方程组Ax=b，其中A为一个方阵；  \n",
    "    (11)lstsq:计算Ax=b的最小二乘解；  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6.数学和统计方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以通过数组上的一组数学函数对整个数组或某个轴向的数据进行统计计算。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "    (1)sum:对数组中全部或某轴向的元素求和。零长度的数组的sum为0；【arr.sum(1)是计算每行的和；arr.sum(0)是计算每列的和】\n",
    "    (2)mean：算术平均值，零长度的数组的mean为NaN；\n",
    "    (3)std、var:分别为标准差和方差，自由度可调(默认为n)；\n",
    "    (4)min、max:最小值和最大值；\n",
    "    (5)argmin、argmax:分别为最小值和最大值的索引；\n",
    "    (6)cumsum:所有元素的累计和；\n",
    "    (7)cumprod:所有元素的累计积；"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "303.825px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
